/**
 * @description admin router
 */

const router = require('koa-router')()
const { SuccessRes } = require('../res-model/index')
const { isProd } = require('../utils/env')

// 中间件
const genValidator = require('../middleware/genValidator')
const { adminInfoSchema } = require('../validator/admin')

// controller
const { login, register } = require('../controller/admin')

// 路由前缀
router.prefix('/api/admin')

// 获取用户信息
router.get('/getUserInfo', async ctx => {
  // koa-jwt 中间件已经自动解析到 ctx.state.user
  const userData = ctx.state.user
  ctx.body = new SuccessRes({
    _id: userData._id,
    nickName: userData.nickName,
    username: userData.username
  })
})

// 登录
router.post('/login', genValidator(adminInfoSchema), async ctx => {
  const { username, password } = ctx.request.body
  const res = await login(username, password)
  ctx.body = res
})

// 初始化几个管理员账号
// ;(async function createTestAdminForDev() {
//   if (isProd) {
//     // 生产环境下
//   } else {
//     // 非生产环境
//     const username = 'admin'
//     const password = '123456'
//     const nickName = '阿猛'
//     await register(username, password, nickName)
//     console.log(`================== 管理员账户：用户名 ${username} 密码 ${password} ==================`)
//   }
// })()

module.exports = router
